import { getUserInfo, getMenu, getSimpleList } from '@/api/user';
import Userinfo from '@/lib/storage/userinfo';
import lodash, { reject } from 'lodash';

export function initUserInfo(): Promise<USER.localInfo> {
  return new Promise(async (resolve) => {
    const localInfo = Userinfo.get();

    const isEmptyLocalData = (object: Record<string, any>) => {
      let isEmpty = false;

      for (const key in object) {
        if (!Object.prototype.hasOwnProperty.call(object, key)) continue;

        if (lodash.isEmpty(object[key])) {
          isEmpty = true;
          break;
        }
      }

      return isEmpty;
    };

    if (!localInfo || lodash.isEmpty(localInfo) || isEmptyLocalData(localInfo)) {
      Promise.all([getUserInfo(), getMenu(), getSimpleList()])
        .then((res) => {
          console.log(res);
          const localData = {
            info: res[0],
            menu: res[1],
            dictionary: res[2],
          };
          Userinfo.set(localData);
          resolve(localData);
        })
        .catch((err) => {
          reject(err);
        });
    } else {
      resolve(localInfo);
    }
  });
}
